
import serial.tools.list_ports

class SerialOperation:
    def __init__(self):
        print("")
        self.refresh()
        self.cur_serial_port = None

    def refresh(self):
        self.serials = serial.tools.list_ports.comports()
        index = 0;
        for port, desc, hwid in self.serials:
            print("{}: {}: {}".format(index, port, desc))
            index += 1

    def isOpen(self):
        return self.cur_serial_port and self.cur_serial_port.is_open

    def getPorts(self):
        return self.serials

    def open(self, index):
        print("open knserial device of {} {}".format(index, self.serials[index].device))
        self.cur_serial_port = serial.Serial(self.serials[index].device, 230400, timeout=0.1)
        return self.cur_serial_port.is_open

    def close(self):
        if self.cur_serial_port and self.cur_serial_port.is_open:
            self.cur_serial_port.close()
        print("close knserial device")

    def sendData(self, buf):
        print("send data {}", format(len(buf)))
        if self.cur_serial_port and self.cur_serial_port.is_open:
            return self.cur_serial_port.write(buf)

    def readData(self):
        print("read data")
        if self.cur_serial_port and self.cur_serial_port.is_open:
            return self.cur_serial_port.read()

    def read(self, n):
        if self.cur_serial_port and self.cur_serial_port.is_open:
            return self.cur_serial_port.read(n)

    def readUntil(self):
        if self.cur_serial_port and self.cur_serial_port.is_open:
            return self.cur_serial_port.read_all()

